Programmatically Add Images To Product Gallery In Magento 2 您所在的位置:网站首页 Programmatically Uploading Images Videos Programmatically Add Images To Product Gallery In Magento 2

Programmatically Add Images To Product Gallery In Magento 2

2024-07-09 13:35| 来源: 网络整理| 查看: 265

How To Programmatically Add Images to Product Gallery in Magento 2 By Sanjay Jethva|

Magento 2,

Perfect pictures encourage more clicks and drive more sales!

As you plan the design of your Magento 2 store, you might think that images are those “nice to have” elements that don’t serve much of a purpose beyond looking good. But images do so much more than paint a pretty picture.

However, to add multiple images to the product at once, you need to add images for each product manually in the default Magento 2. To overcome such manual tasks, you can add images to product gallery in Magento 2 via CSV bulk upload.

With this programmatic method, add multiple images to the product gallery at once and leverage the benefits of having images in an E-commerce store such as:

Stores with more images get more views Images capture attention Convenience in online shopping Improved SERPs Improved click-through rate Boost in social media Boosts SEO value

Now that you know what you’d miss if you do not fill your product gallery with suitable images, get on implementing the below method!

Method to Add Images to Product Gallery in Magento 2:

Create a new php file in the ROOT directory and place the below code to assign images:

1234567891011121314151617181920212223242526272829303132 getObjectManager();     $state = $obj->get('Magento\Framework\App\State');    $state->setAreaCode('frontend');     try    {        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();        $importDir = __DIR__ . '/pub/media/catalog/product'; //This is the directory path from where you have to take the images                $i = '12'; //  It must be product ID for which product it is to be assigned                $product = $objectManager->get('Magento\Catalog\Model\Product')->load($i);                    $id = $product->getId();        $url = $importDir . $product->getImage();        $product->addImageToMediaGallery($url, array('image', 'small_image', 'thumbnail'), true, false);        $product->save();        echo " $id Product Save Succefully";        }    catch(\Exception $e)    {        echo $e->getMessage();        exit;    }

That’s it.

If you have any doubts on the topic, please share them in the Comments section below. I’d be happy to help.

I’d be very grateful if you helped share this helpful post on social media to fellow developers!

Thanks!

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有